package structure.flyweight;

import java.sql.SQLException;
import java.util.Vector;

import structure.bridge.impl.Connection;
import structure.bridge.impl.DriverManager;

public class ConnectionPool {
	private static volatile ConnectionPool instance = null;
	
	private Vector<Connection> pool;

	private String dirver = "structure.bridge.impl.MySQLDriver";
	private String url = "mysql";
	private String name = "mysql";
	private String pwd = "mysql";
	private int poolSize = 20;
	private int max = 30;

	private static volatile int current;

	private ConnectionPool() {
		pool = new Vector<Connection>(poolSize);
		for (int i = 0; i < poolSize; i++) {
			try {
				pool.addElement(createConnection());
				current++;
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static ConnectionPool getInstance() {
		if (instance == null) {
			synchronized (ConnectionPool.class) {
				if (instance == null) {
					instance = new ConnectionPool();
				}
			}
		}
		return instance;
	}

	private Connection createConnection() throws ClassNotFoundException, SQLException {
		Class.forName(dirver);
		return DriverManager.getConnection(url, name, pwd);
	}

	public synchronized int getConnectionCount() {
		return pool.size();
	}

	public synchronized void release(Connection conn) {
		pool.add(conn);
	}

	public synchronized Connection getConnection() throws ClassNotFoundException, SQLException, InterruptedException {
		if (pool.size() != 0) {
			Connection conn = pool.lastElement();
			pool.removeElement(conn);
			return conn;
		}
		if (current < max) {
			Connection conn = createConnection();
			current++;
			return conn;
		}
		wait(20);
		return getConnection();
	}
}
